<template>
  <el-dialog
    v-model="visible"
    width="1000px"
    :title="title"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @closed="dialogClosed"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="转换器名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入转换器名称" />
          </el-form-item>
          <el-form-item label="转换器编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入转换器编码" />
          </el-form-item>
          <el-form-item label="脚本类型" prop="scriptType">
            <el-select v-model="form.scriptType" placeholder="请选择脚本类型">
              <el-option
                v-for="dict in data_conversion_script_type"
                :key="dict.label"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="remark">
            <el-input v-model="form.remark" :rows="4" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="脚本内容" prop="script">
            <div class="w-full">
              <div class="flex flex-row items-center justify-between">
                <div>function transform(data) {</div>
                <el-button type="primary" size="small" @click="handleTest(form)">测试</el-button>
              </div>
              <CodeEditor v-model:value="form.script" />
              <div>}</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>

    <test-transformer v-model="testShow" :current-item="testItem" @save="handleTestSave" />
  </el-dialog>
</template>

<script setup>
  import { ref, computed, watch, defineProps, defineEmits } from 'vue';
  import { addDataTransformer, updateDataTransformer, isCodeUnion } from '@/api/web/db/transformer';
  import { useDict } from '@/utils/dict';
  import { CodeEditor } from '@/components/CodeEditor';
  import TestTransformer from './test-transformer';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => ({}),
    },
  });

  const emits = defineEmits(['update:modelValue', 'success']);

  const visible = computed({
    set(val) {
      emits('update:modelValue', val);
    },
    get() {
      return props.modelValue;
    },
  });

  const { data_conversion_script_type } = useDict('data_conversion_script_type');

  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    code: [
      { required: true, message: '请输入转换器编码', trigger: 'blur' },
      { validator: checkCodeUnion, trigger: 'change' },
    ],
    script: [{ required: true, message: '请输入转换器脚本', trigger: 'blur' }],
    name: [{ required: true, message: '请输入转换器名称', trigger: 'blur' }],
    scriptType: [{ required: true, message: '请选择脚本类型', trigger: 'blur' }],
  });
  const title = ref('');
  const testShow = ref(false);
  const testItem = ref(null);

  watch(visible, (v) => {
    if (v) {
      reset();
      if (props.currentItem?.id) {
        title.value = '修改转换器';
        form.value = { ...props.currentItem };
      } else {
        title.value = '新增转换器';
      }
    }
  });

  function reset() {
    form.value = {
      id: null,
      name: null,
      code: null,
      scriptType: null,
      md5: null,
      remark: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      userId: null,
      script: null,
    };
    formRef.value?.resetFields();
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.value.id) {
          updateDataTransformer(form.value).then(() => {
            modal.msgSuccess('修改成功');
            visible.value = false;
            emits('success');
          });
        } else {
          addDataTransformer(form.value).then(() => {
            modal.msgSuccess('新增成功');
            visible.value = false;
            emits('success');
          });
        }
      }
    });
  }

  function handleTestSave(item) {
    form.value.script = item.script;
  }

  function handleTest() {
    testItem.value = props.currentItem;
    testShow.value = true;
  }

  function checkCodeUnion(_1, _2, callback) {
    isCodeUnion({
      id: form.value.id,
      code: form.value.code,
    }).then((res) => {
      const result = res.data;
      if (result) {
        callback(new Error('转换器编码已存在'));
      } else {
        callback();
      }
    });
  }

  function dialogClosed() {
    title.value = '';
    testShow.value = false;
    testItem.value = null;
    reset();
  }
</script>
